package com.tiemei.demo.json.fastjson;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import static com.tiemei.demo.util.Print.*;

/**
 * String text = ...; // {"name":{"name":"ljw",age:18}} Map<String, User>
 * userMap = JSON.parseObject(text, new TypeReference<Map<String, User>>() {});
 * 
 * @author tiemei.jdk
 * @date 2012-11-7
 */
public class ParseMapList {

	public static void main(String args[]) {
		// demo 1 ok
		p("demo 1-------------------------");
		String text = "{\"key\":{\"name\":\"ljw\",age:18}}";
		Map<String, User> userMap = JSON.parseObject(text, new TypeReference<Map<String, User>>() {});
		p(userMap.get("key"));
		
		// demo 2 ok
		p("demo 2-------------------------");
		text = "{\"key2\":[{\"name\":\"ljw\",age:18},{\"name\":\"ljw2\",age:19}]}";
		Map<String, List<User>> userMap2 = JSON.parseObject(text, new TypeReference<Map<String, List<User>>>() {});
		List<User> userList = userMap2.get("key2");
		for(User e : userList) {
			p(e);
		}
		
		// demo 3 ok
		p("demo 3-------------------------");
		text = "{\"group\":\"group1\", \"users\":[{\"name\":\"ljw\",age:18},{\"name\":\"ljw2\",age:19}]}";
		Users users = JSON.parseObject(text, Users.class);
		p(users);
		
	}
	
	static class Users {
		String group;
		List<User> users;
		
        
        public void setGroup(String group) {
        	this.group = group;
        }
		public void setUsers(List<User> users) {
        	this.users = users;
        }

		@Override
		public String toString() {
			String result = "";
			for(User user:users) {
				result += user.toString()+"\r\n";
			}
			return result;
		}
	};

	static class User {

		private String name;
		private int age;
		
        public void setName(String name) {
        	this.name = name;
        }
        public void setAge(int age) {
        	this.age = age;
        }

		@Override
		public String toString() {
			return "name:" + name + ",age:" + age;
		}
	};
}
